package org.example.higthApiDemo;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.example.task.ConnectElasticsearch;
import org.example.task.ElasticsearchTask;

import java.util.Map;

import static org.example.task.QueryDoc.doQuery;

/**
 * @Author wangf
 * @Description TODO javaAPI - 文档高级查询
 * @Date 2023/3/6 17:17
 */
public class Demo {
    /**
     * 全量查询
     */
    public static final ElasticsearchTask SEARCH_ALL = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            // 查询全部
            sourceBuilder.query(QueryBuilders.matchAllQuery());
        });
    };

    /**
     * 条件查询
     */
    public static final ElasticsearchTask SEARCH_BY_CONDITION = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            // 查询条件：age = 30 || name = wangwu4
            sourceBuilder.query(QueryBuilders.termQuery("age", "20").queryName("wangwu4"));
        });
    };

    /**
     * 分页查询
     */
    public static final ElasticsearchTask SEARCH_BY_PAGING = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            // 当前页起始索引(第一条数据的顺序号) from
            sourceBuilder.from(0);
            // 每页显示多少条 size
            sourceBuilder.size(2);
        });
    };

    /**
     * 查询排序
     */
    public static final ElasticsearchTask SEARCH_WITH_ORDER = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            // 查询全部
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            // 年龄升序
            sourceBuilder.sort("age", SortOrder.ASC);
        });
    };

    /**
     * 组合查询
     */
    public static final ElasticsearchTask SEARCH_BY_BOOL_CONDITION = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            // 查询条件：age = 30 || name = wangwu4
            builder.must(QueryBuilders.termQuery("age", "30"));
            //name=zhangsan
            builder.mustNot(QueryBuilders.termQuery("name", "zhangsan"));
            //可能包含sex=男
            builder.should(QueryBuilders.matchQuery("name", "男"));
            sourceBuilder.query(builder);
        });
    };

    /**
     * 范围查询
     */
    public static final ElasticsearchTask SEARCH_BY_RANGE = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            //查询年龄在30-40之间的数据
            sourceBuilder.query(QueryBuilders.rangeQuery("age").from(30).to(40));
        });
    };

    /**
     * 模糊查询
     */
    public static final ElasticsearchTask SEARCH_BY_FUZZY_CONDITION = client -> {
        doQuery(client, (request, sourceBuilder) -> {
            //name包含wangwu的数据
            sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.ONE));
        });
    };

    /**
     * 高亮查询
     */
    public static final ElasticsearchTask SEARCH_WITH_HIGHLIGHT = client -> {
        SearchRequest request = new SearchRequest().indices("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询方式：高亮查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu1");
        //设置查询方式
        sourceBuilder.query(termQueryBuilder);
        //设置高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置标签前缀
        highlightBuilder.preTags("<font color='red'>");
        //设置标签后缀
        highlightBuilder.postTags("</font>");
        //设置高亮字段
        highlightBuilder.field("name");
        // 设置高亮构建对象
        sourceBuilder.highlighter(highlightBuilder);
        //设置请求体
        request.source(sourceBuilder);
        //客户端发送请求，获取请求响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //解析结果
        SearchHits hits = response.getHits();

        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
            //打印高亮字段
            Map<String, HighlightField> fields = hit.getHighlightFields();
            System.out.println(fields);
        }
    };

    /**
     * 最大查询
     */
    public static final ElasticsearchTask SEARCH_WITH_MAX = client -> {
        SearchRequest request = new SearchRequest().indices("user");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
        request.source(sourceBuilder);

        // 客户端发送请求，获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        for (Aggregation aggregation : response.getAggregations()) {
            System.out.println(aggregation);
        }
        System.out.println(response);

    };

    /**
     * 分组查询
     */
    public static final ElasticsearchTask SEARCH_WITH_GROUP = client -> {
        SearchRequest request = new SearchRequest().indices("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询方式：分组查询
        sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
        request.source(sourceBuilder);
        //客户端发送请求，获取请求响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println(response);
    };

    /**
     * 调用
     *
     * @param args
     */
    public static void main(String[] args) {
        //条件查询
        ConnectElasticsearch.connect(SEARCH_BY_CONDITION);
        //全量查询
        ConnectElasticsearch.connect(SEARCH_ALL);
        //分页查询
        ConnectElasticsearch.connect(SEARCH_BY_PAGING);
        //查询排序
        ConnectElasticsearch.connect(SEARCH_WITH_ORDER);
        //组合查询
        ConnectElasticsearch.connect(SEARCH_BY_BOOL_CONDITION);
        //范围查询
        ConnectElasticsearch.connect(SEARCH_BY_RANGE);
        //模糊查询
        ConnectElasticsearch.connect(SEARCH_BY_FUZZY_CONDITION);
        //高亮查询
        ConnectElasticsearch.connect(SEARCH_WITH_HIGHLIGHT);
        //最大查询
        ConnectElasticsearch.connect(SEARCH_WITH_MAX);
        //分组查询
        ConnectElasticsearch.connect(SEARCH_WITH_GROUP);
    }

}
